package com.example.iread.http;

import android.util.Log;

import com.example.iread.application.MyApplication;
import com.example.iread.bean.ResponseBean;
import com.example.iread.bean.UserBean;
import com.example.iread.util.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Consumer;


public class UserApi {

    private static final ThreadPoolExecutor threadPoolExecutor = MyApplication.getInstance().threadPoolExecutor;


    public static ResponseBean login(Map<String, String> body) {
        return HttpUtil.doPost("/api/user/login", body);
    }

    public static void login(Map<String, String> body, Consumer<ResponseBean> consumer) {
        threadPoolExecutor.execute(() -> consumer.accept(login(body)));
    }

    public static ResponseBean register(Map<String, String> body) {
        return HttpUtil.doPost("/api/user/register", body);
    }

    public static void register(Map<String, String> body, Consumer<ResponseBean> consumer) {
        threadPoolExecutor.execute(() -> consumer.accept(register(body)));
    }

    public static ResponseBean getUserInfo() {
        return HttpUtil.doGet("/api/user/getUserInfo");
    }

    public static void getUserInfo(Consumer<ResponseBean> consumer) {
        threadPoolExecutor.execute(() -> consumer.accept(getUserInfo()));
    }

    public static ResponseBean updateUserInfo(UserBean userBean) {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(userBean);
        Log.i("SoRiya", "jsonStr: " + jsonStr);

        Type type = TypeToken.getParameterized(Map.class, String.class, String.class).getType();
        Map<String, String> map = gson.fromJson(jsonStr, type);
        Log.i("SoRiya", "map: " + map);

        return HttpUtil.doPost("/api/user/updateUserInfo", map);
    }

    public static void updateUserInfo(UserBean userBean, Consumer<ResponseBean> consumer) {
        threadPoolExecutor.execute(() -> consumer.accept(updateUserInfo(userBean)));
    }

}
